<template>
  <div class="invoice-confirm-container">
    <el-card class="confirm-card">
      <template #header>
        <div class="card-header">
          <h2>
            <el-icon><Check /></el-icon>
            确认开票信息
          </h2>
          <div class="header-actions">
            <el-button @click="goBack">
              <el-icon><ArrowLeft /></el-icon>
              返回修改
            </el-button>
          </div>
        </div>
      </template>

      <div class="confirm-content" v-if="invoiceData">
        <!-- 发票基本信息确认 -->
        <div class="confirm-section">
          <h3 class="section-title">
            <el-icon><InfoFilled /></el-icon>
            发票基本信息
          </h3>
          <div class="info-grid">
            <div class="info-item">
              <label>发票类型：</label>
              <span>{{ getInvoiceTypeName(invoiceData.invoiceType) }}</span>
            </div>
            <div class="info-item">
              <label>发票号码：</label>
              <span>{{ invoiceData.invoiceNumber }}</span>
            </div>
            <div class="info-item">
              <label>开票日期：</label>
              <span>{{ invoiceData.issueDate }}</span>
            </div>
            <div class="info-item">
              <label>税率：</label>
              <span>{{ (parseFloat(invoiceData.taxRate) * 100).toFixed(1) }}%</span>
            </div>
          </div>
        </div>

        <!-- 开票方信息确认 -->
        <div class="confirm-section">
          <h3 class="section-title">
            <el-icon><OfficeBuilding /></el-icon>
            开票方信息
          </h3>
          <div class="info-grid">
            <div class="info-item">
              <label>开票方名称：</label>
              <span>{{ invoiceData.issuer.name }}</span>
            </div>
            <div class="info-item">
              <label>纳税人识别号：</label>
              <span>{{ invoiceData.issuer.taxNumber }}</span>
            </div>
            <div class="info-item">
              <label>地址：</label>
              <span>{{ invoiceData.issuer.address }}</span>
            </div>
            <div class="info-item">
              <label>电话：</label>
              <span>{{ invoiceData.issuer.phone }}</span>
            </div>
            <div class="info-item">
              <label>开户银行：</label>
              <span>{{ invoiceData.issuer.bank }}</span>
            </div>
            <div class="info-item">
              <label>银行账号：</label>
              <span>{{ invoiceData.issuer.account }}</span>
            </div>
          </div>
        </div>

        <!-- 收票方信息确认 -->
        <div class="confirm-section">
          <h3 class="section-title">
            <el-icon><User /></el-icon>
            收票方信息
          </h3>
          <div class="info-grid">
            <div class="info-item">
              <label>收票方名称：</label>
              <span>{{ invoiceData.recipient.name }}</span>
            </div>
            <div class="info-item">
              <label>纳税人识别号：</label>
              <span>{{ invoiceData.recipient.taxNumber }}</span>
            </div>
            <div class="info-item">
              <label>地址：</label>
              <span>{{ invoiceData.recipient.address }}</span>
            </div>
            <div class="info-item">
              <label>电话：</label>
              <span>{{ invoiceData.recipient.phone }}</span>
            </div>
            <div class="info-item">
              <label>开户银行：</label>
              <span>{{ invoiceData.recipient.bank }}</span>
            </div>
            <div class="info-item">
              <label>银行账号：</label>
              <span>{{ invoiceData.recipient.account }}</span>
            </div>
          </div>
        </div>

        <!-- 商品信息确认 -->
        <div class="confirm-section">
          <h3 class="section-title">
            <el-icon><Goods /></el-icon>
            商品信息
          </h3>
          <div class="goods-table">
            <table>
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>规格型号</th>
                  <th>单位</th>
                  <th>数量</th>
                  <th>单价</th>
                  <th>金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in invoiceData.goods" :key="index">
                  <td>{{ item.name }}</td>
                  <td>{{ item.specification }}</td>
                  <td>{{ item.unit }}</td>
                  <td>{{ item.quantity }}</td>
                  <td>¥{{ item.unitPrice?.toFixed(2) }}</td>
                  <td>¥{{ calculateAmount(item).toFixed(2) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 金额汇总确认 -->
        <div class="confirm-section">
          <h3 class="section-title">
            <el-icon><Money /></el-icon>
            金额汇总
          </h3>
          <div class="amount-summary">
            <div class="summary-row">
              <span>商品总金额：</span>
              <span class="amount-value">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
            <div class="summary-row">
              <span>税率：</span>
              <span>{{ (parseFloat(invoiceData.taxRate) * 100).toFixed(1) }}%</span>
            </div>
            <div class="summary-row">
              <span>税额：</span>
              <span class="amount-value">¥{{ taxAmount.toFixed(2) }}</span>
            </div>
            <div class="summary-row total">
              <span>价税合计：</span>
              <span class="amount-value">¥{{ totalWithTax.toFixed(2) }}</span>
            </div>
          </div>
        </div>

        <!-- 备注信息确认 -->
        <div class="confirm-section" v-if="invoiceData.remark">
          <h3 class="section-title">
            <el-icon><Edit /></el-icon>
            备注信息
          </h3>
          <div class="remark-content">
            <p>{{ invoiceData.remark }}</p>
          </div>
        </div>

        <!-- 确认操作 -->
        <div class="confirm-actions">
          <div class="agreement-section">
            <el-checkbox v-model="agreedToTerms">
              我已仔细核对上述信息，确认无误，同意开具发票
            </el-checkbox>
          </div>
          
          <div class="action-buttons">
            <el-button @click="goBack" size="large">
              返回修改
            </el-button>
            <el-button 
              @click="submitInvoice" 
              size="large" 
              type="success" 
              :loading="submitting"
              :disabled="!agreedToTerms"
            >
              <el-icon><Check /></el-icon>
              确认开具发票
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

// 接口定义
interface IssuerInfo {
  name: string
  taxNumber: string
  address: string
  phone: string
  bank: string
  account: string
}

interface RecipientInfo {
  name: string
  taxNumber: string
  address: string
  phone: string
  bank: string
  account: string
}

interface GoodsItem {
  name: string
  specification: string
  unit: string
  quantity: number
  unitPrice: number
}

interface InvoiceData {
  invoiceType: string
  invoiceNumber: string
  issueDate: string
  taxRate: string
  issuer: IssuerInfo
  recipient: RecipientInfo
  goods: GoodsItem[]
  remark: string
}

// 路由
const router = useRouter()
const route = useRoute()

// 响应式数据
const submitting = ref(false)
const agreedToTerms = ref(false)
const invoiceData = ref<InvoiceData | null>(null)

// 计算属性
const totalAmount = computed(() => {
  if (!invoiceData.value) return 0
  return invoiceData.value.goods.reduce((total, item) => {
    return total + (item.quantity * item.unitPrice)
  }, 0)
})

const taxAmount = computed(() => {
  if (!invoiceData.value) return 0
  return totalAmount.value * parseFloat(invoiceData.value.taxRate)
})

const totalWithTax = computed(() => {
  return totalAmount.value + taxAmount.value
})

// 方法
const calculateAmount = (item: GoodsItem) => {
  return (item.quantity || 0) * (item.unitPrice || 0)
}

const getInvoiceTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    special: '增值税专用发票',
    normal: '增值税普通发票',
    electronic: '电子普通发票'
  }
  return typeMap[type] || '发票'
}

const goBack = () => {
  router.go(-1)
}

const submitInvoice = async () => {
  if (!agreedToTerms.value) {
    ElMessage.warning('请先同意开票条款')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确认开具发票后无法修改，请再次确认信息无误。',
      '最终确认',
      {
        confirmButtonText: '确认开具',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    submitting.value = true

    // 模拟提交过程
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 跳转到结果页面
    router.push({
      path: '/invoice/result',
      query: { 
        success: 'true',
        invoiceNumber: invoiceData.value?.invoiceNumber,
        amount: totalWithTax.value.toFixed(2)
      }
    })

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发票开具失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

const loadInvoiceData = () => {
  const dataParam = route.query.data as string
  if (dataParam) {
    try {
      invoiceData.value = JSON.parse(dataParam)
    } catch (error) {
      ElMessage.error('数据格式错误')
      router.push('/invoice/form')
    }
  } else {
    ElMessage.warning('未找到发票数据')
    router.push('/invoice/form')
  }
}

// 生命周期
onMounted(() => {
  loadInvoiceData()
})
</script>

<style scoped>
.invoice-confirm-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.confirm-card {
  max-width: 1000px;
  margin: 0 auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.confirm-content {
  padding: 20px;
}

.confirm-section {
  margin-bottom: 30px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  min-width: 120px;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
  flex: 1;
}

.goods-table {
  overflow-x: auto;
}

.goods-table table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.goods-table th,
.goods-table td {
  border: 1px solid #e4e7ed;
  padding: 12px;
  text-align: center;
}

.goods-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #303133;
}

.goods-table tbody tr:hover {
  background: #f5f7fa;
}

.amount-summary {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
  font-size: 16px;
}

.summary-row.total {
  font-weight: 600;
  font-size: 18px;
  color: #e6a23c;
  border-top: 2px solid #e6a23c;
  padding-top: 15px;
  margin-top: 20px;
}

.amount-value {
  font-weight: 600;
  color: #303133;
}

.remark-content {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  border: 1px solid #e4e7ed;
}

.remark-content p {
  margin: 0;
  color: #303133;
  line-height: 1.6;
}

.confirm-actions {
  margin-top: 40px;
  padding: 30px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.agreement-section {
  margin-bottom: 30px;
  text-align: center;
}

.agreement-section .el-checkbox {
  font-size: 16px;
  color: #303133;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .invoice-confirm-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .confirm-content {
    padding: 15px;
  }
  
  .confirm-section {
    padding: 15px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-item label {
    margin-bottom: 5px;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
}

@media (max-width: 480px) {
  .confirm-content {
    padding: 10px;
  }
  
  .confirm-section {
    padding: 10px;
  }
  
  .goods-table {
    font-size: 12px;
  }
  
  .goods-table th,
  .goods-table td {
    padding: 8px;
  }
}
</style>
